package ntd.action;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import cn.hutool.setting.SettingUtil;
import ntd.action.bo.ActionInfo;
import ntd.tool.ToolClass;
import ntd.util.UtilRun;

import java.util.*;

public class ActionManager {

    private static final Map<String, ActionInfo> ACTION_INFO_MAP = new HashMap<>();

    static {
        init();
    }

    public static void register(ActionInfo actionInfo) {
        if (ObjectUtil.isNotNull(actionInfo)) {
            if (ACTION_INFO_MAP.containsKey(actionInfo.getActionCode())) {
                throw new RuntimeException("action code重复，请检查代码！");
            }
            ACTION_INFO_MAP.put(actionInfo.getActionCode(), actionInfo);
        }
    }

    public static ActionInfo get(String action) {
        return ACTION_INFO_MAP.get(action);
    }

    public static List<ActionInfo> list() {
        return new ArrayList<>(ACTION_INFO_MAP.values());
    }

    /**
     * 根据平台类型获取 action
     *
     * @param platformType
     * @return
     */
    public static List<ActionInfo> list(String platformType) {
        return CollectionUtil.filter(list(), actionInfo -> isPlatformType(platformType, actionInfo));
    }

    private static boolean isPlatformType(String platformType, ActionInfo actionInfo) {
        if (StrUtil.isNotBlank(platformType)) {
            return platformType.equals(actionInfo.getPlatform());
        }
        return true;
    }

    public static void init() {
        UtilRun.onlyOne("ntd.action.ActionManager.init", () -> {
            StaticLog.info("Action扫描开始初始化...");
            Set<Class<?>> classes = new HashSet<>();
            classes.addAll(ClassUtil.scanPackageBySuper("ntd", Action.class));
            StaticLog.info("Action扫描[ntd]完成...");
            classes.addAll(ClassUtil.scanPackageBySuper("com", Action.class));
            StaticLog.info("Action扫描[com]完成...");

            for (Class<?> aClass : classes) {
                if (!ClassUtil.isInterface(aClass) && !ClassUtil.isAbstract(aClass)) {
                    Action action = ToolClass.t(aClass);
                    ActionInfo info = action.info();
                    register(info);
                    StaticLog.info("Action注册[{}][{}]完成...", info.getName(), info.getActionCode());
                }
            }
        });
    }

}
